//
//  DeviceDetailVM.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/7/15.
//

import RxSwift
import Combine
import ToastUI
import SwiftUI
import UTEBluetoothRYApi

class DeviceDetailVM: ObservableObject {
    @Published var watchFaces: [UTEModelWatchFace] = []
    @Published var watchFaceParams: UTEModelWatchFaceParams?
    @Published var errorCode: Int = 0
    @Published var uteDict: [AnyHashable: Any] = [:]
    @Published var batteryPer: Int = 0
    @Published var alarmArray: [UTEModelClock] = []
    @Published var errorStr: String?
    @Published var watchFaceImageModel: UTEModelWatchFaceImage?
    private let serverMode: Int = 1
    @Published var takePhoteAction: Int = 0
    @Published var watches: [UTEModelWatchServer] = []
    @Published var error: Error?
    @Published var deviceElement: UTEModelDeviceElement?
    @Published var switchState: Bool = false
    @Published var dailyQuotesStat: Bool = false
    @Published var watchStatus: Bool?//实际状态
    @Published var heartrateState: Bool = false
    @Published var heartrate: Bool?
    private let Heartrate: Int = 195
    @Published var autoStressState: Bool = false
    @Published var autoStress: Bool?
    @Published var lightTime: String?
    @Published var lightTimeState: String?
    @Published var lightTimeList: [String] = []
    @Published var activityState: Bool = false
    @Published var activity: Bool?
    @Published var languageList: [String] = []
    @Published var currentLanguage: String = " "
    @Published var currentLanguageState: String = " "

    
    
    
    
    
    
    init() {
        
        UTEBluetoothMgr.sharedInstance().mgrDevice.onNofityBattery{ battery,uteDict in
            DispatchQueue.main.async {
                    if uteDict != nil {
                        self.batteryPer = battery
                        print("推送的电池电量：\(String(describing: battery))")
                        print("推送的电池电量：\(String(describing: uteDict))")
                    }
            }
        }
        //监听手环相机状态
        UTEBluetoothMgr.sharedInstance().mgrDevice.notifyCamera{ status,errorCode,uteDict in
            DispatchQueue.main.async {
                if uteDict != nil {
                    print("设备相机状态：\(String(describing: status))")
                    print("设备相机状态：\(String(describing: uteDict))")
                    if errorCode == 100000 {
                        self.takePhoteAction = status.rawValue //2拍照 3退出拍照
                    }
                }
            }
        }
        //监听手环生理周期请求
        UTEBluetoothMgr.sharedInstance().mgrDevice.physiological.onNotify {model,uteDict in
            DispatchQueue.main.async {
                if uteDict != nil {
                    print("监听手环生理周期请求：\(String(describing: uteDict))")
                }
            }
        }
        
        //监听心率升高开关+提醒值
        UTEBluetoothMgr.sharedInstance().mgrDevice.onNofityHeartrateRaiseRemind { enable, limit in
            DispatchQueue.main.async {
                if limit != 0 {
                    self.heartrateState = enable
                    self.heartrate = enable
                    print("监听心率升高开关+提醒值：\(String(describing: limit))")
                }
            }
        }
        
        
        //监听设备压力自动测量开关状态
        UTEBluetoothMgr.sharedInstance().mgrDevice.onNotifyAutoStressStatus { enable in
            DispatchQueue.main.async {
                self.autoStressState = enable
                self.autoStress = enable
                print("监听设备压力自动测量开关状态：\(String(describing: enable))")
            }
        }
        
        
        
        
        
    }
    
    
    
    func getWatchFaceParams() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.dial.getWatchFaceParams { [self] (model, errorCode, uteDict) in
            DispatchQueue.main.async {
                self.errorCode = errorCode
                if errorCode == 100000, let model = model {
                    self.watchFaceParams = model
                    self.uteDict = uteDict ?? [:]
                }
            }
        }
    }
    
    func fetchWatchFaces() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.dial.getWatchFaceInfo(NSInteger(serverMode)) { [weak self] (models, errorCode, uteDict) in
                DispatchQueue.main.async {
                    guard let self = self else { return }
                    if errorCode == 100000, let models = models {
                        self.watchFaces = models
                        if let uteDict = uteDict {
                            print("getWatchFaceInfo:\(String(describing: uteDict))")
                        }
                    }
                }
            }
        }
    
    func getImageWatchFaceModel() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.dial.getImageWatchFaceModelBlock { [self] (model, errorCode, uteDict) in
            DispatchQueue.main.async {
                self.errorCode = errorCode
                if errorCode == 100000 {
                    self.watchFaceImageModel = model
                    if uteDict != nil {
                        
                    }
                }
            }
        }
    }
    
    //获取设备信息
    func getDeviceInfo() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.getDeviceInfo { [self] (model, errorCode, uteDict) in
            DispatchQueue.main.async {
                self.errorCode = errorCode
                if errorCode == 100000 {
                    self.deviceElement = model
                }
            }
        }
    }
    
    
    
    
    
    //从服务器获取表盘
    func getWatchFromServer(sdkKey: String, device: UTEModelWatchServer) {
        UTEBluetoothMgr.sharedInstance().mgrDevice.dial.getWatchFromServer(sdkKey,  device: device) { [weak self] watches in
            DispatchQueue.main.async {
                if let watches = watches {
                    self?.watches = watches
                }
            }
        } failure: { error in
            DispatchQueue.main.async {
                if let error = error {
                    self.error = error
                }
            }
        }
    }
    
    
    
    
    //获取电量
    func getBatteryInfo() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.getBatteryInfo {[weak self] percent, errorCode, uteDict in
            DispatchQueue.main.async {
                guard let self = self else { return }
                self.errorCode = errorCode
                if errorCode == 100000 {
                    if uteDict != nil {
                        self.batteryPer = percent
                        print("电池电量：\(String(describing: percent))")
                        print("电池电量：\(String(describing: uteDict))")
                    }
                }
            }
        }
    }
    
    //查找手表 0:关闭 1:开启
    func findWearDevice(cmd:Int) {
        UTEBluetoothMgr.sharedInstance().mgrDevice.setFindWearCmd(Int(cmd)){
            errorCode,uteDict in
            DispatchQueue.main.async {
                if errorCode == 100000 {
                    if uteDict != nil {
                        print("查找手表成功：\(String(describing: uteDict))")
                    }
                }
            }
        }
    }
    
    
    //获取设备闹钟 返回数据不对
    func getAlarmArrayModel() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.getAlarmArrayModel {[weak self] errorCode, modelArray in
            DispatchQueue.main.async {
                guard let self = self else { return }
                if errorCode == 100000 {
                    if let array = modelArray,array.count>0 {
                        self.alarmArray = array
                    }
                }
            }
        }
    }
     
    //获取设备闹钟
    func getAlarmArray() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.getAlarmArray {[weak self] errorCode, uteDict in
            DispatchQueue.main.async {
                guard let self = self else { return }
                if errorCode == 100000 {
                    print("获取设备闹钟：\(String(describing: uteDict))")
                    if let dic = uteDict {
                        let clock:[AlarmModel] = self.parseAlarmData(from: dic) ?? []
                        self.alarmArray = clock.map {$0.toUTEModelClock()}
                    }
                }
            }
        }
    }
    
    func parseAlarmData(from optionalValue: Any) -> [AlarmModel]? {
        guard let dict = optionalValue as? [String: Any],
              let data = dict["data"] as? [String: Any],
              let alarmArray = data["alarmArray"] as? [[String: Any]] else {
            return nil
        }
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: alarmArray)
            let decoder = JSONDecoder()
            return try decoder.decode([AlarmModel].self, from: jsonData)
        } catch {
            print("解析失败: \(error)")
            return nil
        }
    }

    
    
    
    //设置闹钟
    func setAlarmArrayModel(alarms: [UTEModelClock],
                           completion: @escaping (Bool, [AnyHashable: Any]?) -> Void) {
        UTEBluetoothMgr.sharedInstance().mgrDevice.setAlarmArrayModel(alarms) { [weak self] errorCode, uteDict in
            DispatchQueue.main.async {
                guard self != nil else {
                    completion(false, ["error": "对象已释放"])
                    return
                }
                if errorCode == 100000 {
                    completion(true, uteDict)
                } else {
                    completion(false, ["errorCode": errorCode])
                }
            }
        }
    }
    
    
    //删除闹钟
    func delecteAlarmArrayModel(alarm: UTEModelClock,
                           completion: @escaping (Bool) -> Void) {
        let dalarm = UTEModelClock()
        dalarm.index = alarm.index
        dalarm.timeMin = 0
        dalarm.timeHour = 0
        dalarm.cycle = 0
        dalarm.enable = false
        UTEBluetoothMgr.sharedInstance().mgrDevice.setAlarmArrayModel([dalarm]) { [weak self] errorCode, uteDict in
            DispatchQueue.main.async {
                guard self != nil else {
                    completion(false)
                    return
                }
                if errorCode == 100000 {
                    completion(true)
                } else {
                    completion(false)
                }
            }
        }
    }
    
    //恢复出厂设置 0:恢复出厂后重启，1:恢复出厂以及关机
    func resetFactory(type:Int){
        UTEBluetoothMgr.sharedInstance().mgrDevice.resetFactory(type){[weak self]
            errorCode,uteDict in
            DispatchQueue.main.async {
                guard self != nil else {
                    return
                }
                if errorCode == 100000 {
                    self?.errorStr = "恢复出厂成功"
                } else {
                    self?.errorStr = "恢复出厂失败"
                }
            }
        }
    }
    
    //APP解除绑定设备 0断开，1解绑，2未知
    func unboundType(type:Int) {
        UTEBluetoothMgr.sharedInstance().mgrDevice.accountTool.unboundType(type){[weak self] errorCode,uteDict in
            DispatchQueue.main.async {
                guard self != nil else {
                    return
                }
                if errorCode == 100000 {
                    self?.errorStr = "解绑成功"
                } else {
                    self?.errorStr = "解绑失败"
                }
            }
        }
    }
    
    //设置手机相机状态给设备 0:手机进入相机   1：手机打开相机   2：手机退出相机
    func setCameraStatus(eventCode : Int) {
        UTEBluetoothMgr.sharedInstance().mgrDevice.setCameraStatus(eventCode){[weak self] status,errorCode,uteDict in
            DispatchQueue.main.async {
                guard self != nil else {
                    return
                }
                if errorCode == 100000 {
//                    self?.errorStr = "下发相机状态成功"
                } else {
//                    self?.errorStr = "下发相机状态失败"
                }
            }
        }
    }
    
    //获取默认开关状态
    func getDefaultConfiguration() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.getDefaultConfiguration(){[weak self]
            model,errorCode,uteDict in
            DispatchQueue.main.async {
                guard self != nil else {
                    return
                }
                if errorCode == 100000 {
                    print(model ?? "")
                    print("getDefaultConfiguration:\(String(describing: uteDict))")
                } else {

                }
            }
        }
    }
    
    
    //设置女性生理周期开关  0：关闭 固定值31：全开启
    func setMenstrualNotifyAbility(status:Int) {
        UTEBluetoothMgr.sharedInstance().mgrDevice.physiological.setMenstrualNotifyAbility(status){[weak self] errorCode,uteDict in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    print("设置女性生理周期开关：\(String(describing: uteDict))")
                } else {
                    print("设置女性生理周期开关：\(String(describing: uteDict))")
                }
            }
        }
    }
    
    //设置女性生理周期数据
    func setCycleModel(cycleModel:UTEModelCycleData,
                       completion: @escaping (Bool) -> Void){
        UTEBluetoothMgr.sharedInstance().mgrDevice.physiological.setCycleModel(cycleModel) {[weak self] errorCode,uteDict in
            DispatchQueue.main.async {
                guard self != nil else {
                   completion(false)
                    return
                }
                if errorCode == 100000 {
                    completion(true)
                    print("设置女性生理周期数据：\(String(describing: uteDict))")
                } else {
                    completion(false)
                    print("设置女性生理周期数据：\(String(describing: uteDict))")
                }
            }
        }
    }
    
    //设置抬腕亮屏开关状态  true:开 false:关
    func setScreenAutoLight(enable:Bool) {
        UTEBluetoothMgr.sharedInstance().mgrDevice.setScreenAutoLight(enable){[weak self] errorCode,uteDict in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
//                    self?.errorStr = "设置成功"
                    self?.watchStatus = enable
                    print("设置抬腕亮屏开关状态：\(String(describing: uteDict))")
                } else {
                    self?.errorStr = "设置失败"
                    self?.switchState = false
                    print("设置抬腕亮屏开关状态：\(String(describing: uteDict))")
                }
            }
        }
    }
    
    
    //获取抬腕亮屏开关状态 0：关闭；1：开启
    func getScreenAutoLightState() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.getScreenAutoLightState(){[weak self] switchType,switchState,errorCode,uteDict in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    self?.watchStatus = (switchState != 0)
                    self?.switchState = (switchState != 0)
                    self?.dailyQuotesStat = (switchState != 0)
                    print("获取抬腕亮屏开关状态：\(String(describing: uteDict))")
                } else {
                    print("获取抬腕亮屏开关状态：\(String(describing: uteDict))")
                }
            }
        }
    }
    
    //设置心率升高提醒
    func setHeartrateRaiseRemindSwitch(enable:Bool){
        UTEBluetoothMgr.sharedInstance().mgrDevice.setHeartrateRaiseRemindSwitch(enable, limit: Heartrate) {[weak self] errorCode,uteDict in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    print("设置心率升高提醒：\(String(describing: uteDict))")
                } else {
                    print("设置心率升高提醒：\(String(describing: uteDict))")
                    self?.heartrateState = false
                    self?.errorStr = "设置失败"
                }
            }
        }
    }
    
    
    //获取心率升高开关+提醒值
    func getHeartrateRaiseRemindSwitch() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.getHeartrateRaiseRemindSwitch(){[weak self] errorCode,enble,limit in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    self?.heartrateState = enble
                    self?.heartrate = enble
                    print("获取心率升高开关+提醒值：\(String(describing: limit))")
                } else {
                    print("获取心率升高开关+提醒值：\(String(describing: limit))")
                }
            }
        }
    }
    
    //设置压力自动检测开关
    func setAutoStress(enable:Bool){
        UTEBluetoothMgr.sharedInstance().mgrDevice.setAutoStress(enable) {[weak self] errorCode, uteDict in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    print("设置压力自动检测开关：\(String(describing: uteDict))")
                } else {
                    self?.autoStressState = false
                    self?.errorStr = "设置失败"
                    print("设置压力自动检测开关：\(String(describing: uteDict))")
                }
            }
        }
    }
    
    //获取设备压力自动测量开关状态
    func getAutoStress(){
        UTEBluetoothMgr.sharedInstance().mgrDevice.getAutoStress {[weak self] errorCode, enble in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    self?.autoStressState = enble
                    self?.autoStress = enble
                    print("获取设备压力自动测量开关状态：\(String(describing: enble))")
                } else {
                    print("获取设备压力自动测量开关状态：\(String(describing: enble))")
                }
            }
        }
    }
    
    //设置亮屏时长
    func setLightTime(lightTime:Int) {
        UTEBluetoothMgr.sharedInstance().mgrDevice.setLightTime(lightTime) {[weak self] errorCode in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    print("设置亮屏时长：\(String(describing: errorCode))")
                } else {
                    print("设置亮屏时长：\(String(describing: errorCode))")
                }
            }
        }
    }
    
    //获取亮屏时长
    func readLightTime() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.readLightTime {[weak self] lightTime, errorCode in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    self?.lightTime =  String(format:"%ds", lightTime)
                    self?.lightTimeState =  String(format:"%ds", lightTime)
                    print("获取亮屏时长：\(String(describing: lightTime))")
                } else {
                    print("获取亮屏时长：\(String(describing: lightTime))")
                }
            }
        }
    }
    
    //获取亮屏时长设置列表
    func readLightSetTimeList() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.readLightSetTimeList {[weak self] lightTimeList,errorCode in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    let list:[String] = lightTimeList?.compactMap { $0 as? String } ?? []
                    self?.lightTimeList = list.map { "\($0)s" }
                    print("获取亮屏时长设置列表：\(String(describing: lightTimeList))")
                } else {
                    print("获取亮屏时长设置列表：\(String(describing: lightTimeList))")
                }
            }
        }
    }
    
    //设置手环日期格式 1：显示 12 小时格式；2：显示 24 小时格式
    //              1：年-月-日格式；2：月-日-年格式；3：日-月-年格式；4：月-日-星期格式
    func setTimeDisplay(dateType:Int,timeType:Int) {
        UTEBluetoothMgr.sharedInstance().mgrDevice.setTimeDisplay(dateType, timeType: timeType) {[weak self] errorCode, uteDict in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    print("设置手环日期格式：\(String(describing: uteDict))")
                } else {
                    print("设置手环日期格式：\(String(describing: uteDict))")
                }
            }
        }
    }
    
    
    //设置活动提醒信息(久坐，喝水统称)
    func setActivityRemind(enable:Bool,interval:Int8,startTime:Int16,endTime:Int16,cycle:Int8){
        UTEBluetoothMgr.sharedInstance().mgrDevice.setActivityRemind(enable, interval: 30, startTime: (10<<8|0), endTime: (22<<8|0), cycle: 0b111111) {[weak self] errorCode
            , uteDict in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    print("设置活动提醒信息(久坐，喝水统称)：\(String(describing: uteDict))")
                } else {
                    print("设置活动提醒信息(久坐，喝水统称)：\(String(describing: uteDict))")
                }
            }
        }
    }
    
    //获取活动提醒信息(久坐，喝水统称)
    func getActivityRemind(){
        UTEBluetoothMgr.sharedInstance().mgrDevice.getActivityRemind {[weak self] model, errorCode, uteDict in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    if let ml = model {
                        self?.activityState = ml.enable
                        self?.activity = ml.enable
                    }
                    print("获取活动提醒信息(久坐，喝水统称)：\(String(describing: uteDict))")
                } else {
                    print("获取活动提醒信息(久坐，喝水统称)：\(String(describing: uteDict))")
                }
            }
        }
    }
    
    //设置勿扰功能
    func setDNDInfo(info:UTEModeDNDInfo){
        UTEBluetoothMgr.sharedInstance().mgrDevice.setDNDInfo(info) {[weak self] errorCode in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    print("设置勿扰功能：\(String(describing: errorCode))")
                } else {
                    print("设置勿扰功能：\(String(describing: errorCode))")
                }
            }
        }
    }
    
    //获取勿扰状态
    func readDNDInfo() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.readDNDInfo {[weak self] info, errorCode in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    print("获取勿扰状态：\(String(describing: errorCode))")
                } else {
                    print("获取勿扰状态：\(String(describing: errorCode))")
                }
            }
        }
    }
    
  
    
    //获取手环支持语言列表
    func readSupportLanguage() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.readSupportLanguage {[weak self] array, errorCode in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    if let list = array {
                        self?.languageList = mapLanguageIndicesToDescriptions(indices: list)
                        print("获取手环支持语言列表：\(String(describing: mapLanguageIndicesToDescriptions(indices: list)))")
                    }
                } else {
                    print("获取手环支持语言列表：\(String(describing: array))")
                }
            }
        }
    }
    
    //获取当前设备语言
    func readCurrentLanguage() {
        UTEBluetoothMgr.sharedInstance().mgrDevice.readCurrentLanguage {[weak self] UTEDeviceLanguage , errorCode in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    self?.currentLanguage = mapLanguageIndicesToDescription(indice: UTEDeviceLanguage.rawValue)
                    self?.currentLanguageState = mapLanguageIndicesToDescription(indice: UTEDeviceLanguage.rawValue)
                    print("获取当前设备语言：\(String(describing: self?.currentLanguage))")
                } else {
                    print("获取当前设备语言：\(String(describing: UTEDeviceLanguage))")
                }
            }
        }
    }
    
    
    //设置手环语言
    func setLanguageOnly(language:UTEDeviceLanguage) {
        UTEBluetoothMgr.sharedInstance().mgrDevice.setLanguageOnly(language) {[weak self] errorCode, uteDict in
            DispatchQueue.main.async {
                guard self != nil else {return}
                if errorCode == 100000 {
                    print("获取当前设备语言：\(String(describing: uteDict))")
                } else {
                    print("获取当前设备语言：\(String(describing: uteDict))")
                    self?.errorStr = "设置失败"
                }
            }
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
}

